import http from "../../utils/http";

// pages/purchase-record/purchase-record.js
Page({
  data: {
    list: [],
    manufacturers: [],
    selectedManufacturer: '',
    currentPage: 1,
    totalPages: 1,
    isLoading: false,
    isLoadingManufacturer: false,
    searchParams: {
      manufacturer_id: '',
      now_date: ''
    },
    debounceTimer: null
  },

  onLoad() {
    this.loadManufacturers();
    this.loadList();
  },

  loadManufacturers() {
    http.request({
      url: apiConfig.getManufacturerList,
    }).then(res => {
      if (res.status == 200) {
        this.setData({ manufacturers: res.data });
      }
    })
  },

  loadList() {
    if (this.data.isLoading || this.data.currentPage > this.data.totalPages) return;
    
    this.setData({ isLoading: true });
    
    http.request({
      url: apiConfig.getRestockList,
      data: {
        page: this.data.currentPage,
        per_page: 10,
        manufacturer_id: this.data.searchParams.manufacturer_id,
        now_date: this.data.searchParams.now_date
      }
    }).then(res=>{
      if (res.status == 200) {
        const newList = res.data;
        this.setData({
          list: this.data.currentPage === 1? newList : [...this.data.list,...newList],
          totalPages: Math.ceil(res.header['X-Total-Count'] / 10)
        });
      }
    })
    complete: () => this.setData({ isLoading: false })
  },

  bindDateChange(e) {
    this.setData({'searchParams.now_date': e.detail.value}, () => this.reloadList());
  },

  bindManufacturerChange(e) {
    const index = e.detail.value;
    this.setData({
      'searchParams.manufacturer_id': this.data.manufacturers[index]?.id || null,
      selectedManufacturer: this.data.manufacturers[index]?.name || '',
      currentPage: 1
    }, () => this.loadList());
  },

  reloadList() {
    this.setData({ currentPage: 1 }, () => this.loadList());
  },

  onReachBottom() {
    if (!this.data.isLoading && this.data.currentPage < this.data.totalPages) {
      this.setData({ currentPage: this.data.currentPage + 1 }, () => this.loadList());
    }
  },

  // 新增搜索处理
  handleSearch(e) {
    const value = e.detail.value.trim();
    if (this.data.debounceTimer) clearTimeout(this.data.debounceTimer);
    this.data.debounceTimer = setTimeout(() => {
      this.setData({
        'searchParams.now_date': value,
        currentPage: 1
      }, () => this.loadList());
    }, 500);
  }
});